import {EllipsisOutlined, ReloadOutlined} from '@ant-design/icons';
import {PageContainer, ProCard, ProList, StatisticCard} from '@ant-design/pro-components';
import {useNavigate} from '@umijs/max';
import {
  Badge,
  Button,
  Dropdown,
  message,
  Modal, Popconfirm,
  Progress, Space, Tabs,
  Tag,
  Tooltip,
  Typography,
} from 'antd';
import {ListGridType} from 'antd/es/list';
import {PaginationConfig} from 'antd/es/pagination';
import type {Key} from 'antd/lib/table/interface';
import {FC, useEffect, useRef, useState} from 'react';

import CreationForm from '@/pages/Administrative/FileCollection/components/CreationForm';
import SearchForm from '@/pages/Administrative/FileCollection/components/SearchForm';
import {delFileCollectionTask, getFileCollectionTaskList} from '@/services/administrative/file-collection';
import {ROUTES} from '@/utils/enums';
import {CollectionDataType} from '@/utils/types/administrative/file-collection';
import Requirements from "@/pages/Administrative/FileCollection/components/Requirements";

const TAGCOLOR = (key) => {
  const colors = {
    word: 'geekblue',
    ppt: 'red',
    image: 'blue',
    excel: 'orange',
    pdf: 'cyan',
    zip: 'lime',
    all: 'green',
    public: 'green',
    some: '#faad14',
    private: '#ff4d4f',
  }
  return colors[key];
};

const FileCollection: FC = () => {
  // 选中的文件收集任务
  const [selectedKeys, setSelectedKeys] = useState<Key[]>([]);
  // 文件收集任务数据
  const [cardData, setCardData] = useState<CollectionDataType[]>([]);
  // 模态框
  const [isModalOpen, setIsModalOpen] = useState<boolean>(false);
  // 分页
  const [current, setCurrent] = useState<number>(1);
  const [pageSize, setPageSize] = useState<number>(10);
  const [total, setTotal] = useState<number>(0);
  // 路由跳转
  const navigate = useNavigate();
  // 创建文件收集任务
  const createFormRef = useRef<typeof CreationForm>();

  const getList = (
    current: number,
    pageSize: number,
    title?: string,
    file_type?: 'all' | 'image' | 'word' | 'excel' | 'pdf' | 'ppt' | 'zip',
  ) => {

    getFileCollectionTaskList({
      current,
      pageSize,
      title,
      file_type,
    })
      .then((res) => {
        if (res.code === 200) {
          setCardData(res.data?.list as CollectionDataType[]);
          setTotal(res.data.total);
        }
      })
      .catch((err) => {
        message.error(err.message);
      })
      .finally(() => {
        // 刷新表格
      });
  }

  /**
   * 批量删除文件收集任务
   */
  const handleDeleteAll = (key?: string): void => {
    // 请求接口 selectedKeys
    delFileCollectionTask((selectedKeys.length > 0 ? selectedKeys : [key]) as string[])
      .then((response) => {
        if (response.code === 200) {
          console.log(response)
          message.success('删除成功');
          getList(current, pageSize);
        }
      })
      .catch((err) => {
        message.error(err.message);
      })
    setSelectedKeys([]);
  };


  // 创建文件收集任务
  const handleCreateClick = (): void => setIsModalOpen(true);

  const handleEditClick = (id): void => {
    navigate(ROUTES.FILECOLLECTION + '/details?task_id=' + id);
  };

  useEffect((): void => {
    getList(1, 10);
  }, []);




  return (
    <PageContainer header={{title: null}}>

      <ProCard style={{marginBottom: 16, textAlign: 'right'}}>
        <SearchForm onFinish={
          (values) => getList(1, 10, values.title, values.file_type) as (values: any) => (values: any) => void
        }/>
      </ProCard>
      <ProList
        toolBarRender={() => [
          <Button color="primary" variant="solid" key={'new'}
                  onClick={handleCreateClick}>新建任务</Button>,
          <Button color={'default'} variant={'link'} key={'refresh'} onClick={() => getList(1, 10)}><Tooltip
            title={'刷新'}><ReloadOutlined/></Tooltip></Button>]
        }
        dataSource={cardData.map((item) => ({
          ...item,
          key: item.task_id,
          avatar:
            <StatisticCard
              size={'small'}
              style={{backgroundColor: 'transparent'}}
              chart={
                <Progress
                  size={'small'} style={{backgroundColor: 'transparent'}}
                  percent={item?.submitted_number / item?.total_number * 100 ?? 0}
                  type="circle" format={(value) => Math.round(value as number) + '%'}
                />
              }
            />,
          content: <div style={{width: 250, margin: '-40px -10px -10px', height: 150}}>
            {
              item.file_type.includes('all') ?
                <Tag
                  color={TAGCOLOR('all')}>全部文件</Tag> : JSON.parse(item.file_type).map((fileType, index) => (
                  <Tag key={index} color={TAGCOLOR(fileType)}>{fileType}</Tag>
                ))
            }
            <StatisticCard.Group direction={'row'} size={'small'} style={{backgroundColor: 'transparent'}}>
              <StatisticCard
                style={{backgroundColor: 'transparent'}}
                statistic={{
                  title: '已提交',
                  value: item.submitted_number ?? 0,
                  suffix: '个',
                }}
              />
              <StatisticCard
                style={{backgroundColor: 'transparent'}}
                statistic={{
                  title: '总数',
                  value: item.total_number ?? 0,
                  suffix: '个',
                }}
              />
            </StatisticCard.Group>
            <Typography>截止时间: {item.end_time ? String(item.end_time) : '长期有效'}</Typography>
          </div>,
          extra: <Dropdown
            placement="bottomCenter"
            menu={{
              onClick: ({domEvent}) => {
                domEvent.stopPropagation();
                console.log(item)
              },
              items: [
                {
                  label: <Typography.Text type={'success'}>详情</Typography.Text>,
                  key: 'detail', onClick: () => handleEditClick(item.task_id),
                },
                {label: '编辑', key: 'edit'},
                {
                  label:
                    <Popconfirm
                      title={`删除${item.title}`}
                      description={`你确定要删除${item.title}这一项吗？`}
                      onConfirm={() => handleDeleteAll(item.task_id)}
                      okText="Yes"
                      cancelText="No"
                    >
                      <Typography.Text type={'danger'}>删除</Typography.Text>
                    </Popconfirm>,
                  key: 'delete',
                },
              ],
            }}
          >
            <Badge
              color={TAGCOLOR(item.access)} offset={[-35, -10]}
              count={item.access === 'public' ? '公开' : item.access === 'some' ? '指定人员' : '私有'}>
              <Button icon={
                <EllipsisOutlined
                  style={{fontSize: 22, color: 'rgba(0,0,0,0.5)'}}
                  onClick={(e) => e.stopPropagation()}
                />} type={'link'}/>
            </Badge>
          </Dropdown>,
        }))}
        rowKey={(record) => record.task_id}
        metas={{
          title: {
            render: (text) =>
              <Tooltip title={text}>
                <div style={{width: 150, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap'}}>
                  {text}
                </div>
              </Tooltip>,
          },
          subTitle: {},
          type: {},
          avatar: {},
          content: {},
          actions: {cardActionProps: 'extra', dataIndex: 'extra'},
          extra: {},
        }}
        rowSelection={{
          selectedRowKeys: selectedKeys,
          onChange: (selectedRowKeys, selectedRows) => {
            console.log(selectedRowKeys, selectedRows);
            setSelectedKeys(selectedRowKeys);
          },
        }}
        tableAlertOptionRender={() => {
          return (
            <Space size={16}>
              <Button type={'link'} onClick={() => handleDeleteAll()}>
                <Typography.Text type="danger">批量删除</Typography.Text>
              </Button>
              <a onClick={() => setSelectedKeys([])}>取消选择</a>
            </Space>
          );
        }}
        grid={{
          columns: 4,
          xs: '100%',
          sm: '50%',
          md: '40%',
          lg: '20%',
          xl: '10%',
        } as ListGridType}
        onItem={(record: any) => {
          return {
            onClick: () => {
              console.log(record);
            },
          };
        }}
        pagination={{
          current, total, pageSize,
          position: 'bottom',
          // align: 'right',
          onChange: (page, pageSize) => {
            setPageSize(pageSize);
            setCurrent(page);
            getList(page, pageSize);
          },
          style: {
            marginRight: 30,
            marginBottom: 20,
          },
        } as (false & PaginationConfig)}
      >
      </ProList>
      <Modal
        open={isModalOpen} width={800}
        destroyOnClose
        centered onCancel={() => setIsModalOpen(false)}
        footer={null}
      >
        <CreationForm ref={createFormRef} onClose={() => setIsModalOpen(false)} refreshList={() => getList(1, 10)}/>
      </Modal>
    </PageContainer>
  )
};

export default FileCollection;
